package edu.uwo.se2.group3mapapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

public class UserParser extends XmlParser {
	public Response<User> parse(InputStream in)
			throws XmlPullParserException, IOException {
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
			parser.setInput(in, null);
			parser.nextTag();
			return readFeed(parser);
		} finally {
			if (in != null)
				in.close();
		}
	}

	private Response<User> readFeed(XmlPullParser parser)
			throws XmlPullParserException, IOException {
		Log.d("XML", "Starting to read feed");
		Response<User> response = new Response<User>();
		parser.require(XmlPullParser.START_TAG, ns, "response");
	    while (parser.next() != XmlPullParser.END_TAG) {
	        if (parser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        String name = parser.getName();
//	        Log.d("XML", "Count: " + parser.getAttributeCount());

	        // Starts by looking for the entry tag
	        if (name.equals("status")) {
	            Status s = new Status();
	            s.isSuccessful = Boolean.parseBoolean(parser.getAttributeValue(ns, "isSuccessful"));
		        s.content = readText(parser);
		        response.status = s;
	        } else if (name.equals("users")) {
	            parseUsers(response, parser);
	        } else {
	        	skip (parser);
	        }
	    }  
		return response;

	}
	
	private void parseUsers(Response<User> response, XmlPullParser parser) throws XmlPullParserException, IOException {
		// TODO Auto-generated method stub
		parser.require(XmlPullParser.START_TAG, ns, "users");
	    
	    while (parser.next() != XmlPullParser.END_TAG) {
	        if (parser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        
	        String name = parser.getName();
	        if (name.equals("user")) {
	        	User u = new User();
	        	u.id = Integer.parseInt(parser.getAttributeValue(ns, "id"));
	        	u.username = parser.getAttributeValue(ns, "username");
	        	response.list.add(parseUser(u, parser));
	        } else {
	        	skip (parser);
	        }
	    }
	}

	private User parseUser(User u, XmlPullParser parser) throws XmlPullParserException, IOException {
		// TODO Auto-generated method stub
		parser.require(XmlPullParser.START_TAG, ns, "user");
		String x = readText(parser);
    	parser.require(XmlPullParser.END_TAG, ns, "user");
    	return u;
	}
}